package com.distributer.delayqueue.ui;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.distributer.delayqueue.delayqueue.Queue;
import com.distributer.delayqueue.delayqueue.event.RdbStore;
import com.distributer.delayqueue.job.JobStatus;
import com.distributer.delayqueue.job.JobWrapp;



@RestController
@RequestMapping(value = "/")
public class JobController {

    public static final  Logger   LOGGER    = LoggerFactory.getLogger(JobController.class);
    @Resource(name = "redisQueueImpl")
    private  Queue   reidsQueue;
    @Resource(name = "rdbStore")
    private  RdbStore store;	

    @RequestMapping(value = "/push", method = RequestMethod.POST, headers = "content-type=" + MediaType
            .APPLICATION_JSON_VALUE)
    public Map<String, String> push(@RequestBody JobWrapp jobMsg) {
       Map<String, String> result = new HashMap<String, String>();
    	try {
            Assert.notNull(jobMsg.getJobTopic(), "参数topic错误");
            if (StringUtils.isEmpty(jobMsg.getJobId())) {
                jobMsg.setJobId(UUID.randomUUID().toString());
            }
            reidsQueue.putJobMsg(jobMsg);
            result.put("data", JSONObject.toJSONString(jobMsg));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
		return result;
    }
    
    @RequestMapping(value = "/push_2")
    @ResponseBody
    public Map<String, String> push_2() {
       Map<String, String> result = new HashMap<String, String>();
    	try {
    		for (int i = 1; i <= 10; i++) {
    			JobWrapp jobMsg = new JobWrapp();
        		jobMsg.setBody("test-body");
        		jobMsg.setBucketName("test-buket-name");
        		jobMsg.setCreateTime(new Date());
        		jobMsg.setDelayTime(10000*i);
        		jobMsg.setJobId("test_"+i);
        		jobMsg.setJobTopic("test-topic");
        		jobMsg.setStatus(JobStatus.WaitPut.ordinal());
        		jobMsg.setJobKey("test-job-key");
                reidsQueue.putJobMsg(jobMsg);
                result.put(jobMsg.getJobId(), String.valueOf(jobMsg.getDelayTime()));
			}
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
		return result;
    }

}
